#import "PreferencesController.h"
#import "SolarSeekEngine.h"
#import "ShareController.h"
#import "SolarSeekApplication.h"
#import "ApplicationDefaults.h"
#import "Peers.h"
#import <Security/Security.h>

@interface PreferencesController (Private) 
- (void)selectToolbarItem:(id)sender;
@end

@implementation PreferencesController
+ (void)initialize {
	//Install preference defaults
	NSMutableDictionary *appDefaults = [NSMutableDictionary dictionary];
	
	//font sizes
//	[appDefaults setObject:[NSNumber numberWithDouble:12.5] forKey:SolarSeekDefaultSizeFontSourceList];
	
	[appDefaults setObject:[NSNumber numberWithDouble:11.0] forKey:SolarSeekDefaultSizeFontSourceList];
	[appDefaults setObject:[NSNumber numberWithDouble:11.5] forKey:SolarSeekDefaultSizeFontTransferName];
	[appDefaults setObject:[NSNumber numberWithDouble:11.0] forKey:SolarSeekDefaultSizeFontResults];
	[appDefaults setObject:[NSNumber numberWithDouble:11.0] forKey:SolarSeekDefaultSizeFontFriendsList];
	[appDefaults setObject:[NSNumber numberWithDouble:11.0] forKey:SolarSeekDefaultSizeFontChatsList];
	[appDefaults setObject:[NSNumber numberWithDouble:11.0] forKey:SolarSeekDefaultSizeFontChatRoomUserList];
	[appDefaults setObject:[NSNumber numberWithDouble:10.5] forKey:SolarSeekDefaultSizeFontChatRoomList];
	[appDefaults setObject:[NSNumber numberWithDouble:10.5] forKey:SolarSeekDefaultSizeFontGroupChatList];
	[appDefaults setObject:[NSNumber numberWithDouble:0] forKey:SolarSeekDefaultSizeFontChatText];
	
	
	//downloads pane
	
	[appDefaults setObject:@"" forKey:SolarSeekDefaultUsername];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultConnectOnStartup];
	[appDefaults setObject:[NSNumber numberWithInt:0] forKey:SolarSeekDefaultBandwidth];
	[appDefaults setObject:[NSNumber numberWithInt:2] forKey:SolarSeekDefaultShouldRequestConnections];
	[appDefaults setObject:[NSNumber numberWithInt:2034] forKey:SolarSeekDefaultPortStart];
	[appDefaults setObject:[NSNumber numberWithInt:2039] forKey:SolarSeekDefaultPortEnd];
	[appDefaults setObject:@"server.slsknet.org" forKey:SolarSeekDefaultServerName];
	[appDefaults setObject:[NSNumber numberWithInt:2240] forKey:SolarSeekDefaultPortServer];
	[appDefaults setObject:@"SolarSeek tester.\nsoulseek for Mac OS X!\nVisit http://www.fejta.com/solarseek/ for more info."
					forKey:SolarSeekDefaultComment];

	//general pane
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultAutomaticallyCheckForUpdates];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultShowNumberOfNewFilesInDock];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultShowCumulativeBandwidthInformation];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultShowInformationMessages];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultShowUserPicturesWhenAvailable];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultPromptBeforeRemovingPartiallyDownloadedFiles];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultPromptBeforeQuittingWithActiveDownloads];
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultAnimateIconForNewPrivateChat];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultShowNumberOfFilesFoundForCurrentSearch];
	
	//downloads pane
	
	[appDefaults setObject:[@"~/Desktop/SolarSeek/" stringByStandardizingPath] forKey:SolarSeekDefaultPathDownloads];
	[appDefaults setObject:[@"~/Desktop/SolarSeek/Incomplete" stringByStandardizingPath] forKey:SolarSeekDefaultPathDownloadsIncomplete];
	
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultAutomaticallyClearCompletedDownloads];
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultAutomaticallyClearCanceledDownloads];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultSwitchToDownloadViewWhenStarting];
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultCapSpeedDownloads];
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultCapCountDownloads];
	
	[appDefaults setObject:[NSNumber numberWithInt:20] forKey:SolarSeekDefaultSpeedDownloadCap];
	[appDefaults setObject:[NSNumber numberWithInt:5] forKey:SolarSeekDefaultCountDownloadsMax];
	
	[appDefaults setObject:[NSNumber numberWithInt:-1] forKey:SolarSeekDefaultTagIncompleteDownload];
	[appDefaults setObject:[NSNumber numberWithInt:-1] forKey:SolarSeekDefaultTagDownload];
	
	//shares pane
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultShareDefaultDownloadFolder];
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultAutomaticallyClearCompletedUploads];
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultAutomaticallyClearCancelledUploads];
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultCapCountUploads];
	[appDefaults setObject:[NSNumber numberWithBool:NO] forKey:SolarSeekDefaultCapSpeedUploads];
	
	[appDefaults setObject:[NSNumber numberWithInt:2] forKey:SolarSeekDefaultCountUploadsTotalCap];
	[appDefaults setObject:[NSNumber numberWithInt:1] forKey:SolarSeekDefaultCountUploadsPerPeerCap];
	[appDefaults setObject:[NSNumber numberWithInt:2] forKey:SolarSeekDefaultCountPeersTotalCap];
	
	
	[appDefaults setObject:[NSNumber numberWithBool:YES] forKey:SolarSeekDefaultSaveSearches];
	
	//other
	[appDefaults setObject:[NSArray arrayWithObjects:@"SolarSeek",nil] forKey:SolarSeekDefaultChats];
	[appDefaults setObject:[NSArray arrayWithObjects:nil] forKey:SolarSeekDefaultFriends];

		
	//fejta: TODO: font pane
	
	//fejta: TODO: itunes pane
	[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
	[[NSUserDefaultsController sharedUserDefaultsController] setInitialValues:[[appDefaults copy] autorelease]];
}

- (void)awakeFromNib {
	_oldWindow = nil;
	_toolbar = [[NSToolbar alloc] initWithIdentifier:@"com.fejta.SolarSeek.PreferencesToolbar"];
		[_toolbar setDelegate:self];
	[windowPreferences setToolbar:_toolbar];
	[NSApp addObserver:self forKeyPath:@"engine" options:nil context:nil];
	NSToolbarItem *item = [[[NSToolbarItem alloc] initWithItemIdentifier:@"Network"] autorelease];
	[item setLabel:@"Network"];
	[self selectToolbarItem:item];
	[self performSelector:@selector(getPassword) withObject:nil afterDelay:0.03];
	[self performSelector:@selector(getComment) withObject:nil afterDelay:0.03];
	[self performSelector:@selector(getIcon) withObject:nil afterDelay:0.03];
}


- (void)dealloc {
	[_toolbar release];
	[super dealloc];
}

- (void)getPassword {
	[nibTextPassword setStringValue:[NSApp password]];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{
	[self addDefaultShares];
	NSString *u = [[NSUserDefaults standardUserDefaults] stringForKey:SolarSeekDefaultUsername];
	if(u==nil || [u isEqual:@""]) {
		[self setupUsername];
	}
}

#pragma mark Toolbar stuff

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar {
	//return an array with strings of default items in toolbar.
	NSAssert(toolbar == _toolbar,@"Wrong toolbar.");
	
	return [NSArray arrayWithObjects:@"General",@"Network",@"Downloads",@"Shares",@"Fonts",nil];
}

- (NSArray *)toolbarSelectableItemIdentifiers: (NSToolbar *)toolbar {
	return [self toolbarAllowedItemIdentifiers:toolbar];
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar {
	//return an array of strings of possible items in toolbar.
	NSAssert(toolbar == _toolbar,@"Wrong toolbar.");
	return [NSArray arrayWithObjects:@"General",@"Network",@"Downloads",@"Shares",@"Fonts",nil];
}


- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar itemForItemIdentifier:(NSString *)identifier
	willBeInsertedIntoToolbar:(BOOL)flag
{
	NSAssert(toolbar == _toolbar,@"Wrong toolbar.");
	
	NSToolbarItem *item = [[[NSToolbarItem alloc] initWithItemIdentifier:identifier] autorelease];
	[item setLabel:identifier];
	[item setImage:[NSImage imageNamed:[@"preferencePane" stringByAppendingString:identifier]]];
	[item setTarget:self];
	[item setAction:@selector(selectToolbarItem:)];
	return item;
}

#pragma mark actions

- (void)setupPassword {
	NSToolbarItem *item = [[[NSToolbarItem alloc] initWithItemIdentifier:@"Network"] autorelease];
	[item setLabel:@"Network"];
	[self selectToolbarItem:item];
	
	[windowPreferences makeKeyAndOrderFront:self];
}

- (void)setupUsername {
	NSToolbarItem *item = [[[NSToolbarItem alloc] initWithItemIdentifier:@"Network"] autorelease];
	[item setLabel:@"Network"];
	[self selectToolbarItem:item];
	
	[windowPreferences makeKeyAndOrderFront:self];
	
	NSAlert *alert = [NSAlert alertWithMessageText:@"Configure network settings" 
				defaultButton:@"OK" 
				alternateButton:nil
				otherButton:nil
				informativeTextWithFormat:@"Before you can log into the network, you must set up your username and password."];
	[alert beginSheetModalForWindow:windowPreferences modalDelegate:nil didEndSelector:nil contextInfo:nil];
}

- (void)selectToolbarItem:(id)sender {
	if(_oldWindow) {
		NSView *v = [[nibViewPreferences subviews] lastObject]
		;
		[_oldWindow setContentView:v];
	}
	
	NSWindow *other = (NSWindow *)[self valueForKey:[@"window" stringByAppendingString:[sender label]]];
	NSView *v = [other contentView];
	NSRect r = [v frame];
	r.origin.x = r.origin.y = 0;
	[v setFrame:r];
	[nibViewPreferences addSubview:v];
	
	r = [windowPreferences frame];
	NSSize delta = [nibViewPreferences frame].size;
	delta.height -= [other frame].size.height;
	delta.width -= [other frame].size.width;
	
	r.size.height -= delta.height;
	r.size.width -= delta.width;
	
	r.origin.y += (delta.height);
	
	[windowPreferences setFrame:r display:YES animate:YES];
	[windowPreferences setTitle:[other title]];
	[_toolbar setSelectedItemIdentifier:[sender label]];
	
	_oldWindow = other;
}

- (void)addDefaultShares {
	if([NSApp finishedLaunching]==NO)
		[self performSelector:@selector(addDefaultShares) withObject:nil afterDelay:0.5];
	NSEnumerator *e  = [[[NSUserDefaults standardUserDefaults] stringArrayForKey:SolarSeekDefaultShares] objectEnumerator];
	NSString *path;
	while(path = [e nextObject]) {
		[[[NSApp engine] shareController] addFileOrDirectory:[path stringByStandardizingPath]];
	}
}

- (void)addShares:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)info {
	if(returnCode==NSOKButton) { 
		NSArray *a = [panel filenames];
		NSEnumerator *e = [a objectEnumerator];
		NSString *file;
		while(file = [e nextObject])
			[[[NSApp engine] shareController] addFileOrDirectory:file];
		
		NSMutableArray *b = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] stringArrayForKey:SolarSeekDefaultShares]];
		e = [a objectEnumerator];

		while(file = [e nextObject]) {
			if([b containsObject:file]==NO)
				[b addObject:file];
		}
		
		[[[NSUserDefaultsController sharedUserDefaultsController] values] setValue:b forKey:SolarSeekDefaultShares];
			
	}
}

#pragma mark nib actions
- (IBAction)addFolderUpload:(id)sender {
	NSOpenPanel *op = [NSOpenPanel openPanel];
	[op setCanChooseDirectories:YES];
	[op setCanChooseFiles:YES];
	[op setCanCreateDirectories:YES];
	[op setAllowsMultipleSelection:YES];
	[op setNameFieldLabel:@"Choose directories to share:"];
	[op setTitle:@"Choose directories to share"];
	[op setPrompt:@"Add"];
	[op beginSheetForDirectory:nil file:nil types:nil modalForWindow:windowPreferences modalDelegate:self didEndSelector:@selector(addShares:returnCode:contextInfo:) contextInfo:nil];
}

- (void)chooseIconAgain:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	if(returnCode==NSOKButton) {
		[self performSelector:@selector(changeUserIcon:) withObject:self afterDelay:0.0];
	}
}

- (void)changeIcon:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	if(returnCode==NSOKButton)
		[self performSelector:@selector(changeIconWithFilename:) withObject:[panel filename] afterDelay:0.0];
}

	
- (void)setPassword {
	NSString *password = [nibTextPassword stringValue];
	OSStatus rc;
	SecKeychainItemRef keychainItem;
	char *passwordCString = (char *)malloc([password length] * sizeof(char));
	[password getCString:passwordCString maxLength:[password length]];
	rc = SecKeychainFindGenericPassword(NULL,
		   [SolarSeekKeychainService length], [SolarSeekKeychainService cString],
		   [SolarSeekKeychainItem length], [SolarSeekKeychainItem cString],
		   0, NULL, &keychainItem);
	// Password successfully returned (or system said our allocated buffer of "0" was too small)
	if ((rc >= 0) || (rc == errSecBufferTooSmall))
	{
			// Replace password
			rc = SecKeychainItemModifyContent(keychainItem, NULL, [password length], passwordCString);
			if (rc < 0) {
				[[NSAlert alertWithMessageText:@"Could not change password" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"There was an error while trying to update your password in the security keychain.  The Keychain services returned the following result: %d.",rc] beginSheetModalForWindow:windowPreferences modalDelegate:nil didEndSelector:nil contextInfo:nil];
			}
			return;
	}
	else if (rc == errSecItemNotFound)			// Record not found, create.
	{
			NSLog(@"Keychain record not found, creating");
			SecKeychainRef keychain;
			// Open the default keychain
			if ((rc = SecKeychainCopyDefault(&keychain)) < 0)
			{
					[[NSAlert alertWithMessageText:@"Could not access password" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"There was an error while trying to access the security key to change your password.  The Keychain services returned the following result: %d.",rc] beginSheetModalForWindow:windowPreferences modalDelegate:nil didEndSelector:nil contextInfo:nil];
					return;
			}
			// Add the password
			rc = SecKeychainAddGenericPassword(keychain,
				   [SolarSeekKeychainService length], [SolarSeekKeychainService cString],
				   [SolarSeekKeychainItem length], [SolarSeekKeychainItem cString],
				   [password length], passwordCString, &keychainItem);
			if (rc < 0)
			{
					[[NSAlert alertWithMessageText:@"Could not change password" defaultButton:@"OK" alternateButton:nil otherButton:nil informativeTextWithFormat:@"There was an error while trying to change the security key to match your password.  The Keychain services returned the following result: %d.",rc] beginSheetModalForWindow:windowPreferences modalDelegate:nil didEndSelector:nil contextInfo:nil];
			}
			
			return;
	}
	// Unexpected error
	NSLog(@"Error reading keychain %d", rc);
	return;
}


- (void)controlTextDidChange:(NSNotification *)note {
	if([note object]==nibTextPassword) {
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setPassword) object:nil];
		[self performSelector:@selector(setPassword) withObject:nil afterDelay:0.7];
	}
}

- (void)controlTextDidEndEditing:(NSNotification *)note {
	if([note object]==nibTextPassword) {
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setPassword) object:nil];
		[self setPassword];
	}
}

- (void)getIcon {
	NSData *data = [[NSUserDefaults standardUserDefaults] dataForKey:SolarSeekDefaultIcon];
	if(data && [data length] > 0)
		[[[NSApp engine] me] setPicture:data];
}

- (void)getComment {
	NSString *comment = [[NSUserDefaults standardUserDefaults] stringForKey:SolarSeekDefaultComment];
	[[[NSApp engine] me] setComment:comment];
	[nibTextComment setString:comment];
}

- (void)setComment {
	NSString *comment = [nibTextComment string];
	[[[NSApp engine] me] setComment:comment];
	[[NSUserDefaults standardUserDefaults] setObject:comment forKey:SolarSeekDefaultComment];
}

- (void)textDidEndEditing:(NSNotification *)note {
	if([note object]==nibTextComment) {
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setComment) object:nil];
		[self setComment];
	}
}

- (void)textDidBeginEditing:(NSNotification *)note {
	if([note object]==nibTextComment) {
		[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setComment) object:nil];
		[self performSelector:@selector(setComment) withObject:nil afterDelay:0.7];
	}
}



- (void)changeIconWithFilename:(NSString *)filename {
		NSData *filenamedata = [NSData dataWithContentsOfFile:filename];
		SEL again = @selector(chooseIconAgain:returnCode:contextInfo:);
		if([filenamedata length] > 40000) {
				[[NSAlert alertWithMessageText:@"The Image is too big" defaultButton:@"Choose Another" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"When choosing a file to use as your buddy icon, please select an image file that is less than 40,000 bytes in size.  The file at %@ is %d bytes in length.",filename,[filenamedata length]] beginSheetModalForWindow:windowPreferences modalDelegate:self didEndSelector:again contextInfo:nil];
		}
		else {
			NSImage *img = [[NSImage alloc] initWithData:filenamedata];
			if(img) {
				[[[NSApp engine] me] setPicture:filenamedata];
				[[NSUserDefaults standardUserDefaults] setObject:filenamedata forKey:SolarSeekDefaultIcon];
				[img release];
			}
			else {
				[[NSAlert alertWithMessageText:@"Invalid Image File" defaultButton:@"Choose Another" alternateButton:@"Cancel" otherButton:nil informativeTextWithFormat:@"The file you chose (%@) is not an not image file that Mac OS X can decode.  Please choose another file or cancel icon selection.",filename] beginSheetModalForWindow:windowPreferences modalDelegate:self didEndSelector:again contextInfo:nil];
			}
		}
}

- (IBAction)changeUserIcon:(id)sender {
	NSOpenPanel *op = [NSOpenPanel openPanel];
	[op setCanChooseDirectories:NO];
	[op setCanChooseFiles:YES];
	[op setCanCreateDirectories:NO];
	[op setAllowsMultipleSelection:NO];
	[op setNameFieldLabel:@"Choose the image for your buddy icon:"];
	[op setTitle:@"Choose an image for your buddy icon"];
	[op setPrompt:@"Choose"];
	[op beginSheetForDirectory:nil file:nil types:nil modalForWindow:windowPreferences modalDelegate:self didEndSelector:@selector(changeIcon:returnCode:contextInfo:) contextInfo:nil];
}
	

- (void)changeToCustomPath:(NSOpenPanel *)panel returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	id defaults = [[NSUserDefaultsController sharedUserDefaultsController] values];
	if(returnCode==NSOKButton) {
		NSString *path = [[panel directory] stringByStandardizingPath];
		BOOL changeInc = NO;
		if([SolarSeekDefaultPathDownloadsIncomplete isEqual:(NSString *)contextInfo]==NO &&
					[[defaults valueForKey:SolarSeekDefaultPathDownloads] isEqual:[defaults valueForKey:SolarSeekDefaultPathDownloadsIncomplete]]
					) {
			changeInc = YES;
		}
		[defaults setValue:path forKey:(NSString *)contextInfo];
		if(changeInc) 
				[defaults setValue:path forKey:SolarSeekDefaultPathDownloadsIncomplete];
	}

	NSString *str = (NSString *)contextInfo;
	str = [str rangeOfString:@"Incomplete"].location == NSNotFound?SolarSeekDefaultTagDownload:SolarSeekDefaultTagIncompleteDownload;
	[defaults setValue:[NSNumber numberWithInt:-1] forKey:str];
}
		
- (IBAction)changeDownloadPath:(id)sender {
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *newPath = [defaults stringForKey:SolarSeekDefaultPathDownloads];
	switch([sender tag]) {
		case 2: {
			newPath = @"~/Desktop/";
			break;
		}
		case 3: {
			newPath = @"~/Desktop/SolarSeek";
			break;
		}
		case 4: {
			newPath = @"~/Music/";
			break;
		}
		case 5: {
			newPath = @"~/Music/SolarSeek";
			break;
		}
		case 99: {
			NSOpenPanel *op = [NSOpenPanel openPanel];
			[op setCanChooseDirectories:YES];
			[op setCanChooseFiles:NO];
			[op setCanCreateDirectories:YES];
			[op setNameFieldLabel:@"Choose default download directory:"];
			[op setTitle:@"Choose Download Directory"];
			[op setPrompt:@"Choose"];
			[op beginSheetForDirectory:nil file:nil types:nil modalForWindow:windowPreferences modalDelegate:self didEndSelector:@selector(changeToCustomPath:returnCode:contextInfo:) contextInfo:SolarSeekDefaultPathDownloads];
			return;
		}
		default:
			return;
	}
	BOOL changeInc = NO;
	NSRange r = [[defaults stringForKey:SolarSeekDefaultPathDownloadsIncomplete] rangeOfString:[defaults stringForKey:SolarSeekDefaultPathDownloads]];
	NSString *post = @"";
	if(r.location != NSNotFound) {
		changeInc = YES;
		if(r.length < [[defaults stringForKey:SolarSeekDefaultPathDownloadsIncomplete] length]) {
			post = [[defaults stringForKey:SolarSeekDefaultPathDownloadsIncomplete] substringFromIndex:r.length];
		}
	}
	newPath = [newPath stringByStandardizingPath];
	[defaults setObject:newPath forKey:SolarSeekDefaultPathDownloads];
	if(changeInc) 
		[defaults setObject:[newPath stringByAppendingPathComponent:post] forKey:SolarSeekDefaultPathDownloadsIncomplete];
}

- (IBAction)changeIncompleteDownloadPath:(id)sender {
	switch([sender tag]) {
		case 101: {
			NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
			[def setValue:[def stringForKey:SolarSeekDefaultPathDownloads] forKey:SolarSeekDefaultPathDownloadsIncomplete];
			break;
		}
		case 102: {
			NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
			[def setValue:[[def stringForKey:SolarSeekDefaultPathDownloads] stringByAppendingPathComponent:@"Downloading"] forKey:SolarSeekDefaultPathDownloadsIncomplete];
			break; 
		}
		case 199: {
			NSOpenPanel *op = [NSOpenPanel openPanel];
			[op setCanChooseDirectories:YES];
			[op setCanChooseFiles:NO];
			[op setCanCreateDirectories:YES];
			[op setNameFieldLabel:@"Choose incomplete download directory:"];
			[op setTitle:@"Choose Incomplete Download Directory"];
			[op setPrompt:@"Choose"];
			[op beginSheetForDirectory:nil file:nil types:nil modalForWindow:windowPreferences modalDelegate:self didEndSelector:@selector(changeToCustomPath:returnCode:contextInfo:) contextInfo:SolarSeekDefaultPathDownloadsIncomplete];
			return;
		}
	}
}

- (IBAction)removeFolderUpload:(id)sender {
	NSEnumerator *e = [[nibArrayControllerShares selectedObjects] objectEnumerator];
	NSString *path;
	while(path = [e nextObject])
		[[[NSApp engine] shareController] removeFileOrDirectory:path];
	[[[NSUserDefaultsController sharedUserDefaultsController] mutableArrayValueForKeyPath:@"values.solarseekShares"] removeObjectsInArray:[nibArrayControllerShares selectedObjects]];	
}

@end
